﻿using EasyXaf.Sample.ODataService.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.OData.Deltas;
using Microsoft.AspNetCore.OData.Query;
using Microsoft.AspNetCore.OData.Routing.Controllers;

namespace EasyXaf.Sample.ODataService.Controllers;

public class DepartmentsController : ODataController
{
    [EnableQuery]
    public ActionResult<IEnumerable<Department>> Get()
    {
        return MockData.Departments.ToList();
    }

    [EnableQuery]
    public ActionResult<Department> Get([FromRoute] Guid key)
    {
        return MockData.Departments.FirstOrDefault(d => d.Id == key);
    }

    [EnableQuery]
    public ActionResult<Company> GetCompany([FromRoute] Guid key)
    {
        return MockData.Departments.FirstOrDefault(d => d.Id == key)?.Company;
    }

    public IActionResult Post([FromBody] Department department)
    {
        var company = MockData.Companies.FirstOrDefault(c => c.Id == department.Company?.Id);
        company?.Departments.Add(department);
        department.Company = company;
        return Created(department);
    }

    public IActionResult CreateRef([FromRoute] Guid key, [FromRoute] string navigationProperty, [FromBody] Uri link)
    {
        var department = MockData.Departments.SingleOrDefault(d => d.Id == key);
        if (department == null)
        {
            return NotFound();
        }

        if (!Request.TryParseRelatedKey(link, out var relatedKey))
        {
            return BadRequest();
        }

        if (navigationProperty == nameof(Department.Company))
        {
            department.Company?.Departments.Remove(department);

            var company = MockData.Companies.SingleOrDefault(c => c.Id == Guid.Parse(relatedKey));
            company?.Departments.Add(department);
            department.Company = company;
        }

        return NoContent();
    }

    public IActionResult Patch([FromRoute] Guid key, [FromBody] Delta<Department> delta)
    {
        var department = MockData.Departments.SingleOrDefault(d => d.Id == key);
        if (department == null)
        {
            return NotFound();
        }

        delta.Patch(department);

        return Updated(department);
    }

    public IActionResult Delete([FromRoute] Guid key)
    {
        var department = MockData.Departments.SingleOrDefault(d => d.Id == key);
        if (department != null && department.Company != null)
        {
            department.Company.Departments.Remove(department);
        }

        return NoContent();
    }
}
